/*-
 * TestRS232.java
 *
 * Copyright (c) 2007, Stein Gunnar Bakkeby
 * All rights reserved.
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions are met:
 *
 *     * Redistributions of source code must retain the above copyright
 *       notice, this list of conditions and the following disclaimer.
 *     * Redistributions in binary form must reproduce the above copyright
 *       notice, this list of conditions and the following disclaimer in the
 *       documentation and/or other materials provided with the distribution.
 *     * Neither the name of Stein Gunnar Bakkeby nor the names of its
 *       contributors may be used to endorse or promote products derived
 *       from this software without specific prior written permission.
 *
 * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS "AS IS" AND ANY
 * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
 * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
 * DISCLAIMED. IN NO EVENT SHALL THE REGENTS AND CONTRIBUTORS BE LIABLE FOR ANY
 * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
 * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
 * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
 * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
 * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 */
package com.googlecode.attention.rs232;

import java.io.BufferedOutputStream;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.Enumeration;
import java.util.TooManyListenersException;

import com.googlecode.attention.util.Settings;

import gnu.io.*;


/**
 * Test class for RS232.
 *
 * @author Stein Gunnar Bakkeby
 */
public class TestRS232 implements SerialPortEventListener {

  private static SerialPort serialPort;
  private static int dataRate = 9600;
  private SerialPort sp;
  private BufferedReader reader;
  private BufferedOutputStream writer;
  
  /**
   * Constructor for test class.
   * 
   * @param settings Configuration settings.
   */
  public TestRS232(final Settings settings) {
    dataRate = settings.getInteger("baudrate");
  }
  
  /**
   * Constructor for test class.
   */
  public TestRS232() {
    
  }
  
  /**
   * Main class for testing the serial port.
   *
   * @param args
   */
  public static void main(String[] args) {
    //TestRS232 t = new TestRS232(new Settings("src/no/sgb/com/rs232/rs232.properties"));
    TestRS232 t = new TestRS232();
    t.sp = t.getSerialPort();
    try {
      t.reader = new BufferedReader(new InputStreamReader(t.sp.getInputStream()));
      t.writer = new BufferedOutputStream(t.sp.getOutputStream());
      t.sp.addEventListener(t);
      /* Notifies this class when there are data available at RS232. */
      t.sp.notifyOnDataAvailable(true);
    /* Notifies this class when a message has been sent. */
      t.sp.notifyOnOutputEmpty(true);
    } catch (TooManyListenersException e) {
      e.printStackTrace();
    } catch (IOException e) {
      e.printStackTrace();
    }

    try {
      String message = "AT+CMGL=4";
//      message = "at+cpbr=1,200";    // retrieve phonebook
//      message = "at+cpms=ME";       // use phone memory storage
//      message = "at+cpms=SM";       // use sim memory storage
//      message = "AT+CCLK?";         // clock
      message += "\r\n";
      t.writer.write(message.getBytes());
      System.out.println("Sent AT command: \"" + message + "\"");
      t.writer.flush();
//      String line = t.reader.readLine();
//      System.out.println("Output: \"" + line + "\"");
      //writer.close();
    } catch (IOException e) {
      e.printStackTrace();
    }

    try {
      Thread.sleep(100000);
    } catch (InterruptedException e) {
      e.printStackTrace();
    }

    System.exit(0);
  }

  /**
   * This will return a serial port or null if none was found.
   * 
   * @return Serial port or null if none was found.
   */
  @SuppressWarnings("unchecked")
  public SerialPort getSerialPort() {
    CommPortIdentifier portId;
    Enumeration portList = CommPortIdentifier.getPortIdentifiers();
    System.out.println(portList.hasMoreElements());
    while (portList.hasMoreElements()) {
      portId = (CommPortIdentifier) portList.nextElement();
      System.out.println(portId.getName());
      System.out.println(portId.getPortType() == CommPortIdentifier.PORT_SERIAL ? "SERIAL PORT" : "PARALLEL PORT");
      if (portId.getPortType() == CommPortIdentifier.PORT_SERIAL) {;
        //if (portId.getName().equals(portNumber)) {
          try {
            serialPort = (SerialPort) portId.open("SMSGateway", 2000);
            serialPort.setSerialPortParams(dataRate,
                                           SerialPort.DATABITS_8,
                                           SerialPort.STOPBITS_1,
                                           SerialPort.PARITY_NONE);
            return serialPort;
          } catch (PortInUseException e) {
            System.out.println("Port in use");
          } catch (UnsupportedCommOperationException e) {
            System.out.println("Unsupported comm operation exception");
          }
        //}
      }
    }
    return null;
  }

  public void serialEvent(SerialPortEvent evt) {
    int eventType = evt.getEventType();
    System.out.println("evtType: " + eventType);

    try {

      String line = reader.readLine();
      while (line != null) {
        System.out.println(line); line = reader.readLine();
      }
      System.out.println("it actually finished, line must be null");
    } catch (IOException e) {
      e.printStackTrace();
    }

  }
}
